package im.composer.media.sound.misc;

import java.util.Arrays;

import javax.sound.sampled.AudioFormat;

import org.tritonus.share.sampled.FloatSampleBuffer;

public class FloatSamples {

	private FloatSamples() {
	}

	public static final float[] toInterleaveArray(FloatSampleBuffer fsb) {
		float[] interleave;
		if (fsb.getChannelCount() == 1) {
			interleave = Arrays.copyOf(fsb.getChannel(0), fsb.getSampleCount());
		} else {
			interleave = new float[fsb.getChannelCount() * fsb.getSampleCount()];
			int k = 0;
			for (int i = 0; i < fsb.getSampleCount(); i++) {
				for (int j = 0; j < fsb.getChannelCount(); j++) {
					float val = fsb.getChannel(j)[i];
					interleave[k] = val;
					k++;
				}
			}
		}
		return interleave;
	}

	public static final FloatSampleBuffer buildBuffer(float[] samples, AudioFormat format) {
		if (samples.length % format.getChannels() != 0) {
			throw new IllegalArgumentException();
		}
		FloatSampleBuffer fsb = new FloatSampleBuffer(format.getChannels(), samples.length / format.getChannels(), format.getSampleRate());
		if (format.getChannels() == 1)
			System.arraycopy(samples, 0, fsb.getChannel(0), 0, samples.length);
		else
			for (int i = 0, pos = 0; i < samples.length; i++) {
				int j = i % fsb.getChannelCount();
				fsb.getChannel(j)[pos] = samples[i];
				if (j == fsb.getChannelCount() - 1) {
					pos++;
				}
			}
		return fsb;
	}

	public static FloatSampleBuffer buildBuffer(short[] samples, AudioFormat format) {
		if (samples.length % format.getChannels() != 0) {
			throw new IllegalArgumentException();
		}
		FloatSampleBuffer fsb = new FloatSampleBuffer(format.getChannels(), samples.length / format.getChannels(), format.getSampleRate());
		for (int i = 0, pos = 0; i < samples.length; i++) {
			int j = i % fsb.getChannelCount();
			fsb.getChannel(j)[pos] = samples[i] * 1.0f / Short.MAX_VALUE;
			if (j == fsb.getChannelCount() - 1) {
				pos++;
			}
		}
		return fsb;
	}
}
